package com.poisonh.unifiedauth.ui;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;

import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.lzy.okhttputils.model.HttpParams;
import com.poisonh.unifiedauth.R;
import com.poisonh.unifiedauth.adapter.RvProvinceAdapter;
import com.poisonh.unifiedauth.model.ProvinceModel;
import com.poisonh.unifiedauth.utils.ConstantUitls;
import com.poisonh.unifiedauth.utils.GsonUtils;
import com.poisonh.unifiedauth.utils.MyHttpsUtils;
import com.poisonh.unifiedauth.utils.PinyinProvinceComparator;
import com.poisonh.unifiedauth.utils.PinyinUtils;
import com.poisonh.unifiedauth.utils.ToastUtils;
import com.poisonh.unifiedauth.widget.EditTextWithDel;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 省份列表
 * Created by PoisonH on 2016/7/28.
 */
public class ProvinceActivity extends BaseActivity implements RvProvinceAdapter.OnItemClickLitener, View.OnClickListener
{
    private XRecyclerView mXrvProvince;
    private EditTextWithDel mEtSearch;
    private List<ProvinceModel> mList;

    private RvProvinceAdapter mRvProvinceAdapter;

    @Override
    protected void loadContentView(Bundle savedInstanceState)
    {
        setContentView(R.layout.activity_province);
        initTitleView();
        initView();
        getProvince();
        initInput();
    }

    @Override
    protected void initView()
    {
        setTitleTxt("省份");
        mRightBtn.setVisibility(View.GONE);
        mLeftBtn.setOnClickListener(this);
        mEtSearch = (EditTextWithDel) findViewById(R.id.et_search);
        mXrvProvince = (XRecyclerView) findViewById(R.id.xrv_province);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mXrvProvince.setLayoutManager(layoutManager);
        mXrvProvince.setPullRefreshEnabled(false);
        mXrvProvince.setLoadingMoreEnabled(false);

        mRvProvinceAdapter = new RvProvinceAdapter(this);
        mXrvProvince.setAdapter(mRvProvinceAdapter);

        mXrvProvince.setLoadingListener(new XRecyclerView.LoadingListener()
        {
            @Override
            public void onRefresh()
            {
            }

            @Override
            public void onLoadMore()
            {
            }
        });
        mRvProvinceAdapter.setOnItemClickLitener(this);
    }

    /**
     * 获取省份
     */
    private void getProvince()
    {
        HttpParams params = new HttpParams();
        params.put("id", mStrUserId);
        params.put("token", mStrUserToken);
        MyHttpsUtils.post(ConstantUitls.REQUEDT_URL + ConstantUitls.GETPROVINCE, params, new MyHttpsUtils.ResultCallback()
        {
            @Override
            public void onSuccess(String response)
            {
                Message msg = Message.obtain();
                msg.obj = response;
                mHandler.sendMessage(msg);
            }

            @Override
            public void onFailure(String failReason)
            {

            }
        });
    }


    private void initInput()
    {
        //根据输入框输入值的改变来过滤搜索
        mEtSearch.addTextChangedListener(new TextWatcher()
        {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after)
            {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count)
            {
                //当输入框里面的值为空，更新为原来的列表，否则为过滤数据列表
                filterData(s.toString());
            }

            @Override
            public void afterTextChanged(Editable s)
            {
            }
        });
    }

    /**
     * 根据输入框中的值来过滤数据并更新ListView
     *
     * @param filterStr
     */
    private void filterData(String filterStr)
    {
        List<ProvinceModel> mSortList = new ArrayList<>();
        if (TextUtils.isEmpty(filterStr))
        {
            mSortList = mList;
        } else
        {
            mSortList.clear();
            for (ProvinceModel model : mList)
            {
                String name = model.getPRO_NAME();
                if (name.toUpperCase().indexOf(filterStr.toString().toUpperCase()) != -1 || PinyinUtils.getPingYin(name).toUpperCase().startsWith(filterStr.toString().toUpperCase()))
                {
                    mSortList.add(model);
                }
            }
        }
        // 根据a-z进行排序
        Collections.sort(mSortList, new PinyinProvinceComparator());
        mRvProvinceAdapter.update(mSortList);
    }


    Handler mHandler = new Handler()
    {
        @Override
        public void handleMessage(Message msg)
        {
            super.handleMessage(msg);
            mList = new ArrayList<>();
            mList = GsonUtils.parseProvinceData((String) msg.obj);
            if (mList.size() > 0)
            {
                mList = filledData(mList);
                Collections.sort(mList, new PinyinProvinceComparator());
                mRvProvinceAdapter.notif(mList);
            } else
            {
                ToastUtils.showToast(ProvinceActivity.this, "没有更多数据");
                mXrvProvince.setPullRefreshEnabled(true);
            }
        }
    };


    private List<ProvinceModel> filledData(List<ProvinceModel> data)
    {
        List<ProvinceModel> mSortList = new ArrayList<>();
        ArrayList<String> indexString = new ArrayList<>();

        for (int i = 0; i < data.size(); i++)
        {
            ProvinceModel model = new ProvinceModel();
            model.setPRO_NAME(data.get(i).getPRO_NAME());
            model.setPRO_ID(data.get(i).getPRO_ID());
            String pinyin = PinyinUtils.getPingYin(data.get(i).getPRO_NAME());
            String sortString = pinyin.substring(0, 1).toUpperCase();
            if (sortString.matches("[A-Z]"))
            {
                model.setmStrFirstLetter(sortString.toUpperCase());
                if (!indexString.contains(sortString))
                {
                    indexString.add(sortString);
                }
            } else
            {
                model.setmStrFirstLetter("#");
                mSortList.add(model);
            }
            mSortList.add(model);
        }
        Collections.sort(indexString);
        return mSortList;
    }

    @Override
    public void onItemClick(View view, int position)
    {
        Intent mIntent = new Intent();
        mIntent.putExtra("PROID", mList.get(position).getPRO_ID());
        mIntent.putExtra("PRONAME", mList.get(position).getPRO_NAME());
        setResult(100, mIntent);
        finish();
    }

    @Override
    public void onItemLongClick(View view, int position)
    {

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        if (keyCode == KeyEvent.KEYCODE_BACK)
        {
            reBackEmpity();
        }
        return super.onKeyDown(keyCode, event);

    }

    private void reBackEmpity()
    {
        Intent mIntent = new Intent();
        mIntent.putExtra("PROID", "-1");
        mIntent.putExtra("PRONAME", "-1");
        setResult(101, mIntent);
        finish();
    }

    @Override
    public void onClick(View v)
    {
        switch (v.getId())
        {
            case R.id.ib_left_btn:
                reBackEmpity();
                break;
        }
    }
}
